local json = require 'cjson.safe'
local utils = require 'utils'
local limit_conn = require 'resty.limit.count'

local function doFilter()
    local rate = 1
    local scale = 1
    local lim, err = limit_conn.new('limit_store', rate, scale)

    if not lim then
        local result = {
            code = '204';
            msg = 'debug';
            info = 'rate limit error'
        }

        local body = json.encode(result)
        local code = 200

        return body, code
    end

    local ip = ngx.var.remote_addr
    local delay, err = lim:incoming(ip, true)
    if not delay then
        if err == 'rejected' then
            local result = {
                code = '204';
                msg = 'debug';
                info = 'rate limit exceeded'
            }

            local body = json.encode(result)
            local code = 200

            return body, code
        end
    end

    if err < 5 then
        ngx.log(ngx.ERR, 'limit count err < 5')
    end
end

local function httpd()
    local status, result, code = pcall(
        function()
            return doFilter()
        end
    )

    if status then
        if utils.isNotEmpty(result) and utils.isNotEmpty(code) then
            -- js script cross-domain
            ngx.header['Content-Type'] = 'application/json'
            ngx.header['Access-Control-Allow-Origin'] = '*'
            ngx.header['Access-Control-Allow-Headers'] = 'Content-Type, x-bridge-version, x-vendor-id, x-is-test'
            ngx.status = code
            ngx.say(result)
            ngx.exit(code)
        end
    else
        ngx.log(ngx.ERR, result)
        local logstr = string.format("500 INTERNAL_SERVER_ERROR status: %s result: %s.", status, result)
        ngx.status = ngx.HTTP_INTERNAL_SERVER_ERROR
        ngx.say('500 INTERNAL_SERVER_ERROR')
        ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
    end
end

httpd()
